package com.wisdytech.linkdcs.factory.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.github.pagehelper.PageInfo;
import com.wisdytech.common.bean.Filter;
import com.wisdytech.common.constants.CommonConstants;
import com.wisdytech.common.exception.ServiceException;
import com.wisdytech.common.handler.BaseService;
import com.wisdytech.common.utils.BaseUtil;
import com.wisdytech.linkdcs.configuration.dao.ITtEqConfigurationDao;
import com.wisdytech.linkdcs.configuration.model.TtEqConfiguration;
import com.wisdytech.linkdcs.configuration.service.ITtEqConfigurationService;
import com.wisdytech.linkdcs.energy.dao.IEqEnergyDao;
import com.wisdytech.linkdcs.energy.model.EquipmentEnergy;
import com.wisdytech.linkdcs.factory.dao.*;
import com.wisdytech.linkdcs.factory.model.*;
import com.wisdytech.linkdcs.factory.service.TmShopService;
import com.wisdytech.linkdcs.system.dao.ISysOperationDao;
import com.wisdytech.linkdcs.system.model.SysOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Optional;

/**
 * <p>
 * ClassName: TmFactoryServiceImpl
 * <p>
 * Description: 车间管理的业务实现类
 * </p>
 * <p>
 * Author: chenbin
 * </p>
 * <p>
 * Date: 2018年5月4日
 * </p>
 */
@Service("tmShopService")
@Transactional
public class TmShopServiceImpl extends BaseService<TmShopDao, Shop> implements TmShopService{

    /**
     * 注入车间管理dao
     */
	@Resource
	private TmShopDao tmShopDao;
	
    /**
     * 注入车间与工序关联dao
     */
	@Resource
	private TmShopOperationDao tmShopOperationDao;
	
    /**
     * 注入车间与产线关联dao
     */
	@Resource
	private TmShopLineDao tmShopLineDao;
	
	@Resource
	private ITtEqConfigurationService ttEqConfigurationService;

	@Resource
    private ITtEqConfigurationDao ttEqConfigurationDao;
	@Resource
	private TmFactoryDao tmFactoryDao;
	@Resource
	private ISysOperationDao iSysOperationDao;
	
	@Resource
	private TmProductionLineDao tmProductionLineDao;
	
	@Resource
	private IEqEnergyDao iEqEnergyDao;
	
	@Override
	public PageInfo<Shop> listShopByFilter(String shopCode, String shopName, Filter filter) {
		EntityWrapper<Shop> ew =new EntityWrapper<>();
		ew.like("SHOP_CODE", shopCode).like("SHOP_NAME", shopName).eq("del_flag", CommonConstants.DEL_FLAG);
        List<Shop> shopLists = super.beforeList(TmShopDao.class, filter).selectList(ew);
        //遍历每一个车间
		for(Shop shop : shopLists ) {
	        Factory factory = tmFactoryDao.selectById(shop.getFactoryId());
	        shop.setFactoryName(factory.getFactoryName());
			EntityWrapper<ShopOperation> ew2 =new EntityWrapper<>();
			ew2.eq("SHOP_ID", shop.getPkId());
			//通过车间id查询关联对象
			List<ShopOperation> opShopLists = tmShopOperationDao.selectList(ew2);
			//遍历每一个关联对象，
			List<String> opList = new ArrayList<>();
			
			for(ShopOperation opShop : opShopLists) {
				SysOperation op = iSysOperationDao.selectById(opShop.getOpId());
				if (op!=null) {
					opList.add(op.getName());
				}
			}
			String opName = opList.toString();
			String opNameReal = opName.substring(1, opName.lastIndexOf("]"));
			shop.setOperationName(opNameReal);
			
			
			EntityWrapper<ShopLine> ew3 =new EntityWrapper<>();
			ew3.eq("SHOP_ID", shop.getPkId());
			//通过车间id查询关联对象
			List<ShopLine> shopLineLists =tmShopLineDao.selectList(ew3);
			//遍历每一个关联对象，
			List<String> lineList = new ArrayList<>();
			if(shopLineLists != null) {
				for(ShopLine lineShop : shopLineLists) {
					ProductionLine line = tmProductionLineDao.selectById(lineShop.getLineId());
					lineList.add(line.getLineName());
				}
			}
			String lineName = lineList.toString();
			String lineNameReal = lineName.substring(1, lineName.lastIndexOf("]"));
			shop.setLineName(lineNameReal);
		}
        PageInfo<Shop> shopPage = new PageInfo<>(shopLists);
        return shopPage;
	}
	
	
	
	@Override
	public boolean addShop(Shop shop, String loginName) {
        EntityWrapper<Shop> ew =new EntityWrapper<>();
        //验证车间编号的唯一性
        List<Shop> shopList;
        shopList = tmShopDao.selectPage(new Page<Shop>(1, 1), ew.eq("SHOP_CODE", shop.getShopCode()).eq("del_flag", CommonConstants.DEL_FLAG));
        if (!shopList.isEmpty()) {
        	throw new ServiceException("该车间编号被使用");
        }
        //生成产线id
        String pkId = BaseUtil.getUUID();
        //新增车间与工序（一个产线多个工序）
        for (int i = 0; i < shop.getOperationId().split(",").length; i++) {
        	ShopOperation shopOperation = new ShopOperation();
        	shopOperation.setPkId(BaseUtil.getUUID());
        	shopOperation.setShopId(pkId);
        	shopOperation.setOpId(shop.getOperationId().split(",")[i]);
        	shopOperation.setCreateUser(loginName);
        	shopOperation.setCreateDate(new Date());
        	shopOperation.setDelFlag(CommonConstants.DEL_FLAG);
            int shopOperationCount =tmShopOperationDao.insert(shopOperation);
            if (shopOperationCount<=0){
                throw new ServiceException("新增车间与工序关联失败");
            }
        }
        //新增车间与产线（一个车间多个产线）
        if(shop.getLineId() != null && shop.getLineId() != "") {
            for (int i = 0; i < shop.getLineId().split(",").length; i++) {
            	String lineId = shop.getLineId().split(",")[i];
            	if(lineId!=null && lineId!="") {
                	ShopLine shopLine = new ShopLine();
                	shopLine.setPkId(BaseUtil.getUUID());
                	shopLine.setShopId(pkId);
            		shopLine.setLineId(lineId);
                	shopLine.setCreateUser(loginName);
                	shopLine.setCreateDate(new Date());
                	shopLine.setDelFlag(CommonConstants.DEL_FLAG);
                    int shopLineCount =tmShopLineDao.insert(shopLine);
                    if (shopLineCount<=0){
                        throw new ServiceException("新增车间与产线关联失败");
                    }
            	}

            	

            	

            }
        }

        
        //新增车间
        shop.setPkId(pkId);
        shop.setCreateUser(loginName);
        shop.setCreateDate(new Date());
        shop.setDelFlag(CommonConstants.DEL_FLAG);
        int shopCount =tmShopDao.insert(shop);
        if (shopCount<=0){
            throw new ServiceException("新增车间失败");
        }
		return true;
	}



	@Override
	public boolean updateShop(Shop shop, String loginName) {
        EntityWrapper<Shop> ew =new EntityWrapper<>();
        //验证车间编号的唯一性
        List<Shop> shopList;
        shopList = tmShopDao.selectPage(new Page<ProductionLine>(1, 1), ew.eq("SHOP_CODE", shop.getShopCode()).ne("pk_id", shop.getPkId()).eq("del_flag", CommonConstants.DEL_FLAG));
        if (!shopList.isEmpty()) {
        	throw new ServiceException("该车间编号被使用");
        }
    	//先删除车间与工序关联
    	EntityWrapper<ShopOperation> ew1 =new EntityWrapper<>();
    	ew1.eq("SHOP_ID", shop.getPkId());
        int num = tmShopOperationDao.delete(ew1);
        if (num <= 0){
            throw new ServiceException("删除车间与工序关联失败");
        }
        //再新增车间与工序（一个产线多个工序）
        for (int i = 0; i < shop.getOperationId().split(",").length; i++) {
        	ShopOperation shopOperation = new ShopOperation();
        	shopOperation.setPkId(BaseUtil.getUUID());
        	shopOperation.setShopId(shop.getPkId());
        	shopOperation.setOpId(shop.getOperationId().split(",")[i]);
        	shopOperation.setCreateUser(loginName);
        	shopOperation.setCreateDate(new Date());
        	shopOperation.setDelFlag(CommonConstants.DEL_FLAG);
            int shopOperationCount =tmShopOperationDao.insert(shopOperation);
            if (shopOperationCount<=0){
                throw new ServiceException("新增车间与工序关联失败");
            }
        }
        
    	//先删除车间与产线关联
    	EntityWrapper<ShopLine> ew2 =new EntityWrapper<>();
    	ew2.eq("SHOP_ID", shop.getPkId());
        tmShopLineDao.delete(ew2);
        
        //再新增车间与产线（一个车间多个产线）
        if(shop.getLineId() != null && shop.getLineId() != "") {
            for (int i = 0; i < shop.getLineId().split(",").length; i++) {
            	String lineId = shop.getLineId().split(",")[i];
            	if(StringUtils.isNoneEmpty(lineId)) {
                	ShopLine shopLine = new ShopLine();
                	shopLine.setPkId(BaseUtil.getUUID());
                	shopLine.setShopId(shop.getPkId());
                	shopLine.setLineId(shop.getLineId().split(",")[i]);
                	shopLine.setCreateUser(loginName);
                	shopLine.setCreateDate(new Date());
                	shopLine.setDelFlag(CommonConstants.DEL_FLAG);
                	int shopLineCount = tmShopLineDao.insert(shopLine);
                    if (shopLineCount<=0){
                        throw new ServiceException("新增车间与产线关联失败");
                    }
            	}

            }
        }

        //修改车间
        shop.setUpdateUser(loginName);
        shop.setUpdateDate(new Date());
        int shopCount =tmShopDao.updateShopById(shop);
        if (shopCount<=0){
            throw new ServiceException("修改车间失败");
        }
		return true;
	}



	@Override
	public Boolean delShopById(String id) {
		String[] ids = id.split(",");
		for(String pkId : ids) {
            //通过车间的id查询所有车间组态图
            EntityWrapper<TtEqConfiguration> ew = new EntityWrapper<>();
            ew.eq("del_flag", CommonConstants.DEL_FLAG).eq("location_id", pkId).eq("type", "3");
            int num = this.ttEqConfigurationDao.selectCount(ew);
            if(num>0) {
            	throw new ServiceException("所选记录中存在组态图关联");
            }
            
            //通过车间的id查询所有能耗设备
            EntityWrapper<EquipmentEnergy> ew1 = new EntityWrapper<>();
            ew.eq("del_flag", CommonConstants.DEL_FLAG).eq("WORKSHOP", pkId);
            int num1 = this.iEqEnergyDao.selectCount(ew1);
            if(num1>0) {
            	throw new ServiceException("所选记录中存在能耗设备关联");
            }
		}
        for (String pkId : ids) {
        	//删除车间与工序关联
        	EntityWrapper<ShopOperation> ew1 =new EntityWrapper<>();
        	ew1.eq("SHOP_ID", pkId);
            int num = tmShopOperationDao.delete(ew1);
            if (num <= 0){
                throw new ServiceException("删除车间与工序关联失败");
            }
        	//删除车间与产线关联
        	EntityWrapper<ShopLine> ew2 =new EntityWrapper<>();
        	ew2.eq("SHOP_ID", pkId);
	        tmShopLineDao.delete(ew2);

            //删除车间(假删除，改变状态)
            Shop line = new Shop();
            line.setPkId(pkId);
            line.setDelFlag(CommonConstants.DEL_FLAG_TRUE);
            int count =tmShopDao.updateById(line); 
            if (count <= 0){
                throw new ServiceException("删除产线失败");
            }
        }
        return true;
	}



	@Override
	public Shop getShopById(String pkId) {
        Shop shop = tmShopDao.getShopById(pkId);
        if(shop == null) {
        	return null;
		}
        //遍历每一个车间
        Factory factory = tmFactoryDao.selectById(shop.getFactoryId());
        shop.setFactoryName(factory.getFactoryName());
		EntityWrapper<ShopOperation> ew2 =new EntityWrapper<>();
		ew2.eq("SHOP_ID", shop.getPkId());
		//通过车间id查询关联对象
		List<ShopOperation> opShopLists = tmShopOperationDao.selectList(ew2);
		//遍历每一个关联对象，
		List<String> opList = new ArrayList<>();
		List<String> opListId = new ArrayList<>();
		for(ShopOperation opShop : opShopLists) {
			SysOperation op = iSysOperationDao.selectById(opShop.getOpId());
			if(op!=null) {
				opList.add(op.getName());
				opListId.add(op.getPkId());
			}
		}
		String opName = opList.toString();
		String opNameReal = opName.substring(1, opName.lastIndexOf("]"));
		String ids = "";
		for(String id : opListId) {
			ids = ids +","+id;
		}
		if(ids.length()>0) {
			String opIdReal = ids.substring(1);
			shop.setOperationId(opIdReal);
		}
		shop.setOperationName(opNameReal);
		
		
		EntityWrapper<ShopLine> ew3 =new EntityWrapper<>();
		ew3.eq("SHOP_ID", shop.getPkId());
		//通过车间id查询关联对象
		List<ShopLine> shopLineLists =tmShopLineDao.selectList(ew3);
		//遍历每一个关联对象，
		List<String> lineList = new ArrayList<>();
		List<String> lineListId = new ArrayList<>();
		if(shopLineLists != null) {
			for(ShopLine lineShop : shopLineLists) {
				Optional<ProductionLine> optional = Optional.ofNullable(tmProductionLineDao.selectById(lineShop.getLineId()));
				optional.map(ProductionLine::getLineName).ifPresent(lineList::add);
				optional.map(ProductionLine::getPkId).ifPresent(lineListId::add);
			}
		}
		String lineName = lineList.toString();
		String lineNameReal = lineName.substring(1, lineName.lastIndexOf("]"));
		
		String lineIds = "";
		if(!lineListId.isEmpty()) {
			for(String id : lineListId) {
				lineIds = lineIds +","+id;
			}
			String lineIdReal = lineIds.substring(1);
			shop.setLineId(lineIdReal);
		}
		shop.setLineName(lineNameReal);
        return shop;
	}

    @Override
    public List<Shop> listAllShops(String factoryId) {
	    EntityWrapper<Shop> ew = new EntityWrapper<>();
	    ew.setSqlSelect("pk_id","shop_code","shop_name");
	    ew.eq("del_flag",CommonConstants.DEL_FLAG);
	    if(StringUtils.isNotBlank(factoryId)) {
	        ew.eq("factory_id",factoryId);
        }
        List<Shop> list = this.tmShopDao.selectList(ew);
        return list;
    }
}
